require('../../less/controls/checkbox-radio.less');
require('../../less/controls/layout.less');
var React = require('react');
var Checkbox = require('./Checkbox');

module.exports = React.createClass({
	displayName:'CheckboxGroup',
	getInitialState:function(){
		this._sep = this.props.sep || ',';
		this._value = ((typeof this.props.value == 'string')?this.props.value.split(this._sep):this.props.value)||[];
		return {

		}
	},
	componentDidMount:function(){

	},
	removeItemFromArray: function (array, item){
		for(var i = array.length; i--;) {
          	if(array[i] === item) {
              	array.splice(i, 1);
          	}
      	}
	},
	getCheckedItems: function (){

	},
	__onItemChange: function (event, value, checkbox, index){
		var _props = checkbox.props,
			_changeValue = (_props.value||_props.text||'');

		if(value){
			this._value.push(_changeValue);
		} else {
			this.removeItemFromArray(this._value, _changeValue);
		}
		this.props.onChange && this.props.onChange(event, {
			index: index,
			changeValue: _changeValue,
			value: this._value,
			checked: value,
			checkbox: checkbox
		}, this);
	},
	disabled: function (value) {
		this.props.disabled = value;
	},
	render: function(){
		var _disabled = this.props.disabled||false,
			_value = this._value;

		return (
			<div className={"c-checkbox-group " + (this.props.className||'') + ' layout-' + (this.props.layout||'inline')} style={this.props.style}>
				{
					this.props.data && this.props.data.map(function (item, index) {
						var _item = (typeof item=='string')?{ text: item }:item,
							_itemValue = _item.value || _item.text;
						if(_value.indexOf(_itemValue)!=-1){
							_item.checked = true;
						} else {
							_item.checked = false;
						}
						_item.disabled = _disabled;
						return <Checkbox key={index} {..._item} onChange={(event, value, checkbox)=>this.__onItemChange(event, value, checkbox, index)} />;
					}.bind(this))
				}
			</div>
		);
	}
});
